/* Assignment Notebook
 * Created By: Amanda Rush
 * www.AmandaRush.com
 * Version 1.1
 * Release: 4/14/2011
 */

package com.captainkat.assignmentnotebook;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.Calendar;
import java.util.TimeZone;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import android.net.Uri;
import android.database.Cursor;
import android.content.ContentUris;
import android.content.ContentValues;
import android.text.format.*;



//Date Picker
import android.app.Dialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.widget.DatePicker;
import android.widget.TimePicker;

public class AssignmentEditExisting extends Activity implements OnClickListener {
	protected TextView enterDate;
	protected TextView enterTime;
	protected TextView enterEndTime;
	protected TextView title;
	protected TextView desc;
	protected TextView save;
	protected TextView cancel;
	protected TextView delete;
	protected Calendar currentDate;
	protected TimeZone timezone;
	protected String calendarURI;
	protected SimpleDateFormat dateFormat;
	protected SimpleDateFormat timeFormat;
	protected Calendar newEventDate;
	protected Calendar newEventEndDate;
	
	

	//get calendar Uri
	protected Uri calendars;
	//set the calendar id
	protected String calendarId = "-1";
	//get events uri
	protected Uri eventsUri;
	//gets instances uri
	protected Uri instancesUri;
	
	//Date Picker
	static final int DATE_DIALOG_ID = 0;
	static final int START_TIME_DIALOG_ID = 1;
	static final int END_TIME_DIALOG_ID = 2;
	
	//event instances
	EventHolder eventHolder;
	
	public AssignmentEditExisting() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setRequestedOrientation(1);  
		setContentView(R.layout.editexisting);
		
		//get android version
		checkVersion();
		
		eventHolder= new EventHolder();
		
		//get today's date on the calendar
		currentDate = Calendar.getInstance();
		//set up a new event date
		newEventDate=Calendar.getInstance();
		newEventEndDate=Calendar.getInstance();
		
		
		//GET Passed-in-date OUT OF BUNDLE
		Bundle b = this.getIntent().getExtras();
		calendarId = b.getString("calendarId");
		currentDate.setTimeInMillis(b.getLong("time"));
		eventHolder.eid = b.getString("eid");
		timezone = TimeZone.getDefault();
		currentDate.setTimeZone(timezone);
		
		//set up a new event date
		newEventDate.setTimeZone(timezone);
		newEventEndDate.setTimeZone(timezone);
		
		//set up date formats
		dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		timeFormat = new SimpleDateFormat("HH:mm");
		
		//set up View objects and ClickListeners
		enterDate = (TextView) findViewById(R.id.edate);
		enterDate.setOnClickListener(this);
		enterTime = (TextView) findViewById(R.id.etime);
		enterTime.setOnClickListener(this);
		enterEndTime = (TextView) findViewById(R.id.eendtime);
		enterEndTime.setOnClickListener(this);
		
		
		title = (TextView) findViewById(R.id.eenterTitle);
		title.setOnClickListener(this);
		desc = (TextView) findViewById(R.id.eenterDesc);
		desc.setOnClickListener(this);
		save = (TextView) findViewById(R.id.esave);
		save.setOnClickListener(this);
		cancel = (TextView) findViewById(R.id.ecancel);
		cancel.setOnClickListener(this);
		delete = (TextView) findViewById(R.id.edelete);
		delete.setOnClickListener(this);
	
		
		//Put the current date on the screen
		enterDate.setText(dateFormat.format(currentDate.getTime()));
		enterTime.setText(timeFormat.format(currentDate.getTime()));
		enterEndTime.setText(timeFormat.format(currentDate.getTime()));
		
		
		drawScreen();
		
		
	}
	
	@Override
	public void onClick(View v)  {
		Uri updateEventsUri = ContentUris.withAppendedId(eventsUri, Long.parseLong(eventHolder.eid));
		
		Bundle b;
	switch (v.getId()) { //what to do when you press one of the buttons
		
		case R.id.edate:
			showDialog(DATE_DIALOG_ID);
			break;
		case R.id.etime:
			showDialog(START_TIME_DIALOG_ID);
			break;
		case R.id.eendtime:
			showDialog(END_TIME_DIALOG_ID);
			break;
	
			
		case R.id.esave:
			
		
			ContentValues event = new ContentValues();
			//set which calendar
			event.put("calendar_id", calendarId);
			//put event data in 
			event.put("title", title.getText().toString());
			event.put("description", desc.getText().toString());
			event.put("dtstart", newEventDate.getTimeInMillis());
			//event.put("allDay", 0);
			//event.put("event_id", eventIdPassedIn);
			event.put("dtend", newEventEndDate.getTimeInMillis());
			
			//Update the database
			getContentResolver().update(updateEventsUri,event,null,null);
			
			//Create the intent
			Intent saveAsn = new Intent(v.getContext(), DailyView.class);
			//pass along the time
			b = new Bundle();
			b.putLong("time",newEventDate.getTimeInMillis());
			saveAsn.putExtras(b);
            startActivity(saveAsn);
            finish();
			break;
		case R.id.ecancel:
			//go back
			Intent cancelAsn = new Intent(v.getContext(), DailyView.class);
			//pass along the time: so it goes back to the date we were on
			b = new Bundle();
			b.putLong("time",currentDate.getTimeInMillis());
			cancelAsn.putExtras(b);
            startActivity(cancelAsn);
            finish();
            break;
		case R.id.edelete:
			//delete the record
			getContentResolver().delete(updateEventsUri,null,null);
			Intent deleteAsn = new Intent(v.getContext(), DailyView.class);
			b = new Bundle();
			//make it go back to the date we were on
			b.putLong("time", currentDate.getTimeInMillis());
			deleteAsn.putExtras(b);
			startActivity(deleteAsn);
			finish();
			break;
			
	}
	}
	
	
	
	public void checkVersion() {
		if (Integer.parseInt(Build.VERSION.SDK) <=7) //if lower than or equal to Android 2.1
			calendarURI = "calendar";
		else
			calendarURI = "com.android.calendar";
		
		//put in the correct content provider for that version
		calendars = Uri.parse("content://"+calendarURI+"/calendars");
		eventsUri = Uri.parse("content://"+calendarURI+"/events");
		instancesUri = Uri.parse("content://"+calendarURI+"/instances/when");
		
	}
	
public void drawScreen() {		
		//Build instances uri for ONE DAY STILL NEEDS TIME ZONE?
		Uri.Builder builder = Uri.parse("content://"+calendarURI+"/instances/when").buildUpon();
		long daysofar = (currentDate.getTimeInMillis()+timezone.getOffset(currentDate.getTimeInMillis())) % DateUtils.DAY_IN_MILLIS;
		long dayleft = DateUtils.DAY_IN_MILLIS - daysofar;
		ContentUris.appendId(builder, currentDate.getTimeInMillis() - daysofar);
		ContentUris.appendId(builder, currentDate.getTimeInMillis() + dayleft);
		
		//make selection and projection
		String[] projection = new String[] {"calendar_id","event_id","title","description" ,"dtstart","dtend" };
		String selection = "event_id="+eventHolder.eid;
		
		Cursor managedCursor = managedQuery(builder.build(), projection, selection,null,null);
		
		if (managedCursor.moveToFirst()) {
			int calIdColumn = managedCursor.getColumnIndex("calendar_id");
			int startColumn = managedCursor.getColumnIndex("dtstart");
			int titleColumn = managedCursor.getColumnIndex("title");
			int descColumn = managedCursor.getColumnIndex("description");
			int endColumn = managedCursor.getColumnIndex("dtend");
			//get start date + time
			eventHolder.dtstart = managedCursor.getLong(startColumn);
			newEventDate.setTimeInMillis(eventHolder.dtstart);
			enterDate.setText(dateFormat.format(newEventDate.getTime()));
			enterTime.setText(timeFormat.format(newEventDate.getTime()));

			eventHolder.dtend = managedCursor.getLong(endColumn);
			newEventEndDate.setTimeInMillis(eventHolder.dtend);
			enterEndTime.setText(timeFormat.format(newEventEndDate.getTime()));
			
			//eventHolder
			eventHolder.calendarId=managedCursor.getString(calIdColumn);
			calendarId=eventHolder.calendarId;
			//get title
			eventHolder.title = managedCursor.getString(titleColumn);
			//get description
			eventHolder.description = managedCursor.getString(descColumn);
			
			//set text
			title.setText(eventHolder.title);	
			desc.setText(eventHolder.description);
			
		}
		
		
	}

public void changeIntentTime() {
	//edit the intent
	Bundle b = new Bundle();
	b.putLong("time", newEventDate.getTimeInMillis());
	b.putString("eid", eventHolder.eid);
	b.putString("calendarId", eventHolder.calendarId);
	this.getIntent().replaceExtras(b);
}

//DATE PICKER THINGS
// Creating dialog


private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
// onDateSet method
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
	//String date_selected = String.valueOf(monthOfYear)+"/"+String.valueOf(dayOfMonth)+"/"+String.valueOf(year);
	
	newEventDate.set(Calendar.MONTH, monthOfYear);
	newEventDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
	newEventDate.set(Calendar.YEAR, year);
	newEventEndDate.set(Calendar.MONTH, monthOfYear);
	newEventEndDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
	newEventEndDate.set(Calendar.YEAR, year);
	
//show the date on the screen
	enterDate.setText(dateFormat.format(newEventDate.getTime()));
	changeIntentTime();

}
};

//Time Picker things

private TimePickerDialog.OnTimeSetListener startTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		
		newEventDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
		newEventDate.set(Calendar.MINUTE, minute);
		newEventEndDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
		newEventEndDate.set(Calendar.MINUTE, minute);
				
		//show the time on the screen
		enterTime.setText(timeFormat.format(newEventDate.getTime()));
		changeIntentTime();
	}
	};
	
private TimePickerDialog.OnTimeSetListener endTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			
			newEventEndDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
			newEventEndDate.set(Calendar.MINUTE, minute);
		
			//show the time on the screen
			enterEndTime.setText(timeFormat.format(newEventEndDate.getTime()));
		}
		};	
	@Override
	protected Dialog onCreateDialog(int id) {
	
	int cyear = newEventDate.get(Calendar.YEAR);
	int cmonth = newEventDate.get(Calendar.MONTH);
	int cday = newEventDate.get(Calendar.DAY_OF_MONTH);
	int chour = newEventDate.get(Calendar.HOUR_OF_DAY);
	int cminute = newEventDate.get(Calendar.MINUTE);
	int ehour = newEventEndDate.get(Calendar.HOUR_OF_DAY);
	int eminute = newEventEndDate.get(Calendar.MINUTE);
	switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener,  cyear, cmonth, cday);
		case START_TIME_DIALOG_ID:
			return new TimePickerDialog(this, startTimeSetListener, chour, cminute, true);
		case END_TIME_DIALOG_ID:
			return new TimePickerDialog(this, endTimeSetListener,ehour, eminute, true);

		}
	return null;
	}

}
